﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace WebSocketServer
{

    public enum ServerLogLevel { Nothing, Subtle, Verbose };
    public delegate void ClientConnectedEventHandler(WebSocketConnection sender, EventArgs e);

    public class WebSocketServer
    {
        private const string STR_SecWebSocketVersion = "Sec-WebSocket-Version";
        private const string STR_ServerName = "localhost";// "ClueGa.me";
        #region private members
        private string webSocketOrigin;     // location for the protocol handshake
        private string webSocketLocation;   // location for the protocol handshake
        #endregion

        public event ClientConnectedEventHandler ClientConnected;

        /// <summary>
        /// TextWriter used for logging
        /// </summary>
        public TextWriter Logger { get; set; }     // stream used for logging

        /// <summary>
        /// How much information do you want, the server to post to the stream
        /// </summary>
        public ServerLogLevel LogLevel = ServerLogLevel.Subtle;

        /// <summary>
        /// Gets the connections of the server
        /// </summary>
        public List<WebSocketConnection> Connections { get; private set; }

        /// <summary>
        /// Gets the listener socket. This socket is used to listen for new client connections
        /// </summary>
        public Socket ListenerSocker { get; private set; }

        /// <summary>
        /// Get the port of the server
        /// </summary>
        public int Port { get; private set; }


        public WebSocketServer(int port, string origin, string location)
        {
            Port = port;
            Connections = new List<WebSocketConnection>();
            webSocketOrigin = origin;
            webSocketLocation = location;
        }

        /// <summary>
        /// Starts the server - making it listen for connections
        /// </summary>
        public void Start()
        {
            // create the main server socket, bind it to the local ip address and start listening for clients
            ListenerSocker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            string Address = "127.0.0.1";//"74.208.68.146";  //ClueGa.me
            IPEndPoint ipLocal = new IPEndPoint( IPAddress.Parse(Address), Port);
            ListenerSocker.Bind(ipLocal);
            ListenerSocker.Listen(100);
            LogLine(DateTime.Now + "> server stated on " + ListenerSocker.LocalEndPoint, ServerLogLevel.Subtle);
            ListenForClients();
        }

        // look for connecting clients
        private void ListenForClients()
        {
            ListenerSocker.BeginAccept(new AsyncCallback(OnClientConnect), null);
        }

        private void OnClientConnect(IAsyncResult asyn)
        {
            // create a new socket for the connection
            var clientSocket = ListenerSocker.EndAccept(asyn);

            // shake hands to give the new client a warm welcome
            ShakeHands(clientSocket);

            // oh joy we have a connection - lets tell everybody about it
            LogLine(DateTime.Now + "> new connection from " + clientSocket.LocalEndPoint, ServerLogLevel.Subtle);



            // keep track of the new guy
            var clientConnection = new WebSocketConnection(clientSocket);
            Connections.Add(clientConnection);
            clientConnection.Disconnected += new WebSocketDisconnectedEventHandler(ClientDisconnected);

            // invoke the connection event
            if (ClientConnected != null)
                ClientConnected(clientConnection, EventArgs.Empty);

            if (LogLevel != ServerLogLevel.Nothing)
                clientConnection.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);



            // listen for more clients
            ListenForClients();
        }

        void ClientDisconnected(WebSocketConnection sender, EventArgs e)
        {
            Connections.Remove(sender);
            LogLine(DateTime.Now + "> " + sender.ConnectionSocket.LocalEndPoint + " disconnected", ServerLogLevel.Subtle);
        }

        void DataReceivedFromClient(WebSocketConnection sender, DataReceivedEventArgs e)
        {
            Log(DateTime.Now + "> data from " + sender.ConnectionSocket.LocalEndPoint, ServerLogLevel.Subtle);
            Log(": " + e.Data + "\n" + e.Size + " bytes", ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Subtle);
        }


        /// <summary>
        /// send a string to all the clients (you spammer!)
        /// </summary>
        /// <param name="data">the string to send</param>
        public void SendToAll(string data)
        {
            Connections.ForEach(a => a.Send(data));
        }

        /// <summary>
        /// send a string to all the clients except one
        /// </summary>
        /// <param name="data">the string to send</param>
        /// <param name="indifferent">the client that doesn't care</param>
        public void SendToAllExceptOne(string data, WebSocketConnection indifferent)
        {
            foreach (var client in Connections)
            {
                if (client != indifferent)
                    client.Send(data);
            }
        }

        /// <summary>
        /// Takes care of the initial handshaking between the the client and the server
        /// </summary>
        private void ShakeHands(Socket conn)
        {
            String webSocketsVersion = "";

            using (var stream = new NetworkStream(conn))
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            {
                //read handshake from client (no need to actually read it, we know its there):
                LogLine("Reading client handshake:", ServerLogLevel.Verbose);
                var headers = new Dictionary<string, string>();
                string line = string.Empty;
                while ((line = ReadLine(stream)) != string.Empty)
                {
                    Console.WriteLine("\t{0}", line);
                    var tokens = line.Split(new char[] { ':' }, 2);
                    if (!string.IsNullOrEmpty(line) && tokens.Length > 1)
                    {
                        headers[tokens[0]] = tokens[1].Trim();
                    }
                    LogLine(line, ServerLogLevel.Verbose);
                }
                // check websockets version
                // send handshake to the client according to the websockets version requested
                if (headers.ContainsKey(STR_SecWebSocketVersion))
                {
                    webSocketsVersion = headers[STR_SecWebSocketVersion];
                }
                {
                    switch (webSocketsVersion)
                    {
                        case "":
                            writer.Write(HandShake00(stream, headers, String.Format("ws://{0}:{1}/websession", STR_ServerName, Port), "sample"));
                            break;
                        case "06":
                            writer.Write(HandShake06(ComputeWSAccept(headers)));
                            break;
                        case "13":
                            writer.Write(HandShake13("sample", ComputeWSAccept(headers)));
                            break;
                        default:
                            LogLine(String.Format("protocol handling error! {0} = {1}", STR_SecWebSocketVersion, webSocketsVersion), ServerLogLevel.Subtle);
                            break;
                    }
                }
            }


            // tell the nerds whats going on
            LogLine("Sending handshake:", ServerLogLevel.Verbose);
            LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
            LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
            LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
            LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
            LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Verbose);

            LogLine("Started listening to client", ServerLogLevel.Verbose);
            //conn.Listen();
        }

        private static String ComputeWSAccept(Dictionary<string, string> headers)
        {
            var key = headers["Sec-WebSocket-Key"];
            var decodedKey = Convert.FromBase64String(key);
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            string wsAccept = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")));
            return wsAccept;
        }

        private static String HandShake13(string protocol, string wsAccept)
        {
            String response = "HTTP/1.1 101 Switching Protocols" + Environment.NewLine +
                              "Upgrade: websocket" + Environment.NewLine +
                              "Connection: Upgrade" + Environment.NewLine +
                              "Sec-WebSocket-Accept: " + wsAccept + Environment.NewLine +
                              "Sec-WebSocket-Protocol: " + protocol + Environment.NewLine +
                              Environment.NewLine;
            return response;
        }

        private static String HandShake06(string wsAccept)
        {
            String response = "HTTP/1.1 101 Switching Protocols" + Environment.NewLine +
                              "Upgrade: websocket" + Environment.NewLine +
                              "Connection: Upgrade" + Environment.NewLine +
                              "Sec-WebSocket-Accept: " + wsAccept + Environment.NewLine +
                              Environment.NewLine;
            return response;
        }

        private static String HandShake00(NetworkStream stream, Dictionary<string, string> headers, string urlLocation, string protocol)
        {
            List<byte> result = new List<byte>();
            var key = new byte[8];
            stream.Read(key, 0, key.Length);

            var key1 = headers["Sec-WebSocket-Key1"];
            var key2 = headers["Sec-WebSocket-Key2"];

            var numbersKey1 = Convert.ToInt64(string.Join(null, Regex.Split(key1, "[^\\d]")));
            var numbersKey2 = Convert.ToInt64(string.Join(null, Regex.Split(key2, "[^\\d]")));
            var numberSpaces1 = CountSpaces(key1);
            var numberSpaces2 = CountSpaces(key2);

            var part1 = (int)(numbersKey1 / numberSpaces1);
            var part2 = (int)(numbersKey2 / numberSpaces2);

            result.AddRange(GetBigEndianBytes(part1));
            result.AddRange(GetBigEndianBytes(part2));
            result.AddRange(key);

            Byte[] handshake = null;
            using (var md5 = MD5.Create())
            {
                handshake = md5.ComputeHash(result.ToArray());
            }
            String response = "HTTP/1.1 101 WebSocket Protocol Handshake" + Environment.NewLine +
                               "Upgrade: WebSocket" + Environment.NewLine +
                               "Connection: Upgrade" + Environment.NewLine +
                               "Sec-WebSocket-Origin: " + headers["Origin"] + Environment.NewLine +
                               "Sec-WebSocket-Location: " + urlLocation + Environment.NewLine +
                               "Sec-WebSocket-Protocol: " + protocol + Environment.NewLine +
                               Encoding.UTF8.GetString(handshake) + Environment.NewLine +
                               Environment.NewLine;
            return response;
        }

        static int CountSpaces(string key)
        {
            return key.Length - key.Replace(" ", string.Empty).Length;
        }

        static byte[] GetBigEndianBytes(int value)
        {
            var bytes = 4;
            var buffer = new byte[bytes];
            int num = bytes - 1;
            for (int i = 0; i < bytes; i++)
            {
                buffer[num - i] = (byte)(value & 0xffL);
                value = value >> 8;
            }
            return buffer;
        }

        static string ReadLine(Stream stream)
        {
            var sb = new StringBuilder();
            var buffer = new List<byte>();
            while (true)
            {
                buffer.Add((byte)stream.ReadByte());
                var line = Encoding.ASCII.GetString(buffer.ToArray());
                if (line.EndsWith(Environment.NewLine))
                {
                    return line.Substring(0, line.Length - 2);
                }
            }
        }

        private void Log(string str, ServerLogLevel level)
        {
            if (Logger != null && (int)LogLevel >= (int)level)
            {
                Logger.Write(str);
            }
        }

        private void LogLine(string str, ServerLogLevel level)
        {
            Log(str + "\r\n", level);
        }


/*
        private byte[] receivedDataBuffer;
        private byte[] FirstByte;
        private byte[] LastByte;

        private void Read(IAsyncResult status)
        {
            if (!ListenerSocker.Connected) return;
            try
            {
                // Web Socket protocol: messages are sent with 0x00 and 0xFF as padding bytes
                System.Text.ASCIIEncoding decoder = new System.Text.ASCIIEncoding();
                int startIndex = 0;
                int endIndex = 0;

                // Search for the start byte
                while (receivedDataBuffer[startIndex] == FirstByte[0]) startIndex++;
                // Search for the end byte
                endIndex = startIndex + 1;
                while (receivedDataBuffer[endIndex] != LastByte[0]) endIndex++;

                // Get the message
                string messageReceived = decoder.GetString(receivedDataBuffer, startIndex, endIndex - startIndex);
                Logger.Write("Message received [\"" + messageReceived + "\"]");
                // Generate the event

                //if (DataReceived != null) DataReceived(messageReceived, EventArgs.Empty);
                //Array.Clear(receivedDataBuffer, 0, receivedDataBuffer.Length);
                //ConnectionSocket.BeginReceive(receivedDataBuffer, 0, receivedDataBuffer.Length, 0, new AsyncCallback(Read), null);
            }
            catch
            {
               // ClientDisconnected();
            }
        }
*/




    }
}